<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" showBack> </pageHeader>
  <a-result v-if="error" status="error" title="MPR计算失败">
    <template #subtitle> 请联系管理员 </template>

    <template #extra>
      <a-space>
        <a-button type="primary" @click="router.back()">Back</a-button>
      </a-space>
    </template>
  </a-result>
  <div
    v-show="hidden && !error"
    style="
      width: 100%;
      height: 200px;
      display: flex;
      justify-content: center;
      margin-top: 50px;
    "
  >
    <div
      style="
        display: flex;
        flex-direction: column;
        width: 500px;
        padding: 50px;
        border-radius: 20px;
        box-shadow: 0 0 4px #a8a8a8;
      "
    >
      <p style="font-size: 16px; padding: 0; margin: 0 0 10px 0">
        正在生产分析结果
      </p>
      <p style="font-size: 12px; padding: 0; margin: 0 0 10px 0">
        分析结果倒计时：{{ responseTime }}s
      </p>
      <a-progress
        :percent="(10 - responseTime) / 10"
        :type="'line'"
        size="large"
      />
    </div>
  </div>
  <div v-show="!hidden">
    <div class="main">
      <div class="title">
        <div class="icon"></div>
        <p>成品基本信息</p>
      </div>
      <div class="table">
        <TableTurn
          ref="tableRef"
          :args="{ bordered: { wrapper: true, cell: true } }"
          :table-data="getData"
          :isShowPagination="false"
        >
          <a-table-column :width="80" align="center">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="生产订单"
            data-index="number"
          >
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="销售订单"
            data-index="saleOrderNumber"
          >
            <template #cell="{ record }">
              {{ record.saleOrderNumber ? record.saleOrderNumber : '-' }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="物料编码"
            data-index="spec"
          >
            <template #cell="{ record }">
              {{ record.material.number }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="物料名称"
            data-index="basicName"
          >
            <template #cell="{ record }">
              {{ record.material.name }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="规格型号"
            data-index="repairerName"
          >
            <template #cell="{ record }">
              {{ record.material.spec }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="基本单位"
            data-index="emergencyLevel"
          >
            <template #cell="{ record }">
              {{ record.material.basicUnit }}
            </template>
          </a-table-column>
          <!-- <a-table-column
            :width="150"
            align="center"
            title="生产批次"
            data-index="repairerName"
          >
            <template #cell="{ record }">
              {{ `${dayjs(record.planBeginAt).format('YYYY-MM-DD')}` }}
            </template>
          </a-table-column> -->
          <a-table-column
            :width="150"
            align="center"
            title="生产订单数量"
            data-index="planProduceNumber"
          >
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="紧急等级"
            data-index="repairerName"
          >
            <template #cell="{ record }">
              <p
                :style="{
                  color: emergencyLevel.filter(
                    (ele) => ele.id === record?.emergencyLevel
                  )[0]?.color,
                }"
              >
                {{
                  emergencyLevel.filter(
                    (ele) => ele.id === record?.emergencyLevel
                  )[0]?.value
                }}
              </p>
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="工艺路线"
            data-index="repairerName"
          >
            <template #cell="{ record }">
              <p>{{
                record?.material?.productModel?.routerName
                  ? record?.material?.productModel?.routerName
                  : '暂无'
              }}</p>
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="关联产品BOM"
            data-index="repairerName"
          >
            <template #cell="{ record }">
              <p>{{
                record?.material?.bomCode ? record?.material?.bomCode : '暂无'
              }}</p>
            </template>
          </a-table-column>
          <!-- <a-table-column
            :width="150"
            align="center"
            title="客户名称"
            data-index="repairerName"
          >
          </a-table-column> -->
          <a-table-column
            :width="150"
            align="center"
            title="计划开工时间"
            data-index="planBeginAt"
          >
            <template #cell="{ record }">
              {{ `${dayjs(record.planBeginAt).format('YYYY-MM-DD')}` }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="计划结束时间"
            data-index="planEndAt"
          >
            <template #cell="{ record }">
              {{ `${dayjs(record.planEndAt).format('YYYY-MM-DD')}` }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            align="center"
            title="交货日期"
            data-index="repairerName"
          >
            <template #cell>
              {{ '-' }}
            </template>
          </a-table-column>
        </TableTurn>
      </div>
      <div class="title">
        <div class="icon"></div>
        <p>组件需求明细</p>
      </div>
      <div class="table">
        <a-table
          :scroll="{
            x: '100%',
            y: globalParameters.windowHeight - 300,
          }"
          :bordered="{ wrapper: true, cell: true }"
          :columns="columns1"
          :data="moduleData.data"
          :pagination="false"
        >
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #attributeName="{ record }">
            {{ record.attribute === 1 ? '自制' : '委外' }}
          </template>
        </a-table>
      </div>
      <div class="title">
        <div class="icon"></div>
        <p>{{ submit ? '物料分析' : '成品基本信息' }}</p>
      </div>
      <div class="table" v-if="!submit">
        <a-tabs type="card-gutter" auto-switch>
          <a-tab-pane :key="1" title="全部">
            <a-table
              :pagination="false"
              :scroll="{
                x: '100%',
                y: globalParameters.windowHeight - 300,
              }"
              :bordered="{ wrapper: true, cell: true }"
              :columns="columns2"
              :data="productDataAll.data"
            >
              <template #index="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #inTransitNumber="{ record }">
                {{ record.inTransitNumber }}
              </template>
              <template #dosage="{ record }">
                {{ record.dosage }}
              </template>
              <template #wastage="{ record }">
                {{ record.wastage }}
              </template>
              <template #materialStatus="{ record }">
                <div
                  class="status"
                  :class="{ lack: record.materialStatus === 1 }"
                >
                  <p></p>
                  {{ record.materialStatus === 1 ? '满足' : '缺料' }}
                </div>
              </template>
              <template #satisfiedProduceNumber="{ record }">
                {{ record.satisfiedProduceNumber }}
              </template>
              <template #outOfStockNumber="{ record }">
                {{ record.outOfStockNumber }}
              </template>
              <template #recommendPurchaseNumber="{ record }">
                <a-input v-model="record.recommendPurchaseNumber"></a-input>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane :key="2" title="缺料">
            <a-table
              :pagination="false"
              :scroll="{
                x: '100%',
                y: globalParameters.windowHeight - 300,
              }"
              :bordered="{ wrapper: true, cell: true }"
              :columns="columns2"
              :data="productDataLack.data"
            >
              <template #index="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #inTransitNumber="{ record }">
                {{ record.inTransitNumber }}
              </template>
              <template #dosage="{ record }">
                {{ record.dosage }}
              </template>
              <template #wastage="{ record }">
                {{ record.wastage }}
              </template>
              <template #materialStatus="{ record }">
                <div
                  class="status"
                  :class="{ lack: record.materialStatus === 1 }"
                  ><p></p>
                  {{ record.materialStatus === 1 ? '满足' : '缺料' }}
                </div>
              </template>
              <template #satisfiedProduceNumber="{ record }">
                {{ record.satisfiedProduceNumber }}
              </template>
              <template #outOfStockNumber="{ record }">
                {{ record.outOfStockNumber }}
              </template>
              <template #recommendPurchaseNumber="{ record }">
                <a-input v-model="record.recommendPurchaseNumber"></a-input>
                <!-- {{ record.recommendPurchaseNumber }} -->
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>
      <a-space style="margin-bottom: 20px" v-if="submit">
        <!-- <a-button type="primary" @click="materielModalVisible = true">
          <template #icon>
            <icon-plus />
          </template>

          <template #default>新增</template>
        </a-button>
        <a-button> 删除 </a-button> -->
      </a-space>
      <div class="table" v-if="submit">
        <a-table
          :pagination="false"
          :scroll="{
            x: '100%',
            y: globalParameters.windowHeight - 300,
          }"
          :bordered="{ wrapper: true, cell: true }"
          :columns="columns2"
          :data="productDataLack.data"
        >
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #inTransitNumber="{ record }">
            {{ record.inTransitNumber }}
          </template>
          <template #dosage="{ record }">
            {{ record.dosage }}
          </template>
          <template #wastage="{ record }">
            {{ record.wastage }}
          </template>
          <template #materialStatus="{ record }">
            <div class="status" :class="{ lack: record.materialStatus === 1 }">
              <p></p>
              {{ record.materialStatus === 1 ? '满足' : '缺料' }}
            </div>
          </template>
          <template #satisfiedProduceNumber="{ record }">
            {{ record.satisfiedProduceNumber }}
          </template>
          <template #outOfStockNumber="{ record }">
            {{ record.outOfStockNumber }}
          </template>
          <template #recommendPurchaseNumber="{ record }">
            <a-input v-model="record.recommendPurchaseNumber"></a-input>
          </template>
        </a-table>
      </div>
    </div>
    <div class="foot">
      <a-space style="margin-right: 20px">
        <a-button @click="router.back()"> 取消 </a-button>
        <a-button v-if="!submit" @click="submit = true" type="primary">
          物料需求
        </a-button>
        <a-button v-else type="primary" @click="confirm"> 确认提交 </a-button>
      </a-space>
    </div>
  </div>
  <materielModal
    title="物料产品选择"
    v-model:visible="materielModalVisible"
    @changeVisible="changeVisible"
    @searcchMaterialData="updateMaterialData"
  />
</template>

<script setup lang="ts">
  import dayjs from 'dayjs';
  import { reactive, ref } from 'vue';
  import materielModal from '@/components/materielModal/index.vue';
  import pageHeader from '@/components/page-header/index.vue';
  import { useRouter, useRoute } from 'vue-router';
  import { useGlobalParametersStore, useBuyStore } from '@/store';
  import {
    GetProduceOrdersMrp,
    GetProduceOrderDetails,
    GetProduceMaterialsMrp,
  } from '@/api/produce-management/produce-list/index';
  import type { ProduceOrder } from '@/api/produce-management/produce-list/type';
  import { Message } from '@arco-design/web-vue';
  import { cloneDeep } from 'lodash';

  const emergencyLevel = [
    { id: 1, value: '一般', color: '#009933' },
    { id: 2, value: '紧急', color: '#409eff' },
    { id: 3, value: '加急', color: '#ff8000' },
    { id: 4, value: '特急', color: '#ff0000' },
  ];
  const error = ref(false);
  const buyStore = useBuyStore();
  const materielModalVisible = ref(false);
  const router = useRouter();
  const route = useRoute();
  const id = ref(Number(route.query.id));
  const submit = ref(false);
  const successful = ref(false);
  const title: string = 'MRP运算';
  const breadCrumb: string[] = ['生产管理', '生产订单'];
  let tableRef = ref();
  const hidden = ref(true);
  const responseTime = ref(10);
  const productBasic = reactive<{ data: ProduceOrder[] }>({ data: [] });
  const moduleData = reactive<any>({ data: [] });
  const productDataAll: any = reactive({ data: [] });
  const productDataLack: any = reactive({ data: [] });
  let setTime = 1000;
  const globalParameters = useGlobalParametersStore();
  const columns1: any = [
    {
      title: '序号',
      dataIndex: 'name',
      align: 'center',
      slotName: 'index',
    },
    {
      title: '组件码',
      dataIndex: 'number',
      align: 'center',
    },
    {
      title: '组件名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '规格型号',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '基本单位',
      dataIndex: 'basicName',
      align: 'center',
    },
    {
      title: '需求数量',
      dataIndex: 'demandNumber',
      align: 'center',
    },
    {
      title: '生产类型',
      dataIndex: 'attribute',
      align: 'center',
      slotName: 'attributeName',
    },
    {
      title: '库存量',
      dataIndex: 'name',
      align: 'center',
      children: [
        {
          title: '库存总量',
          dataIndex: 'totalStock',
          align: 'center',
        },
        {
          title: '已占用库存量',
          dataIndex: 'occupiedStock',
          align: 'center',
        },
        {
          title: '空闲库存量',
          dataIndex: 'freeStock',
          align: 'center',
        },
      ],
    },
    {
      title: '可交货数量',
      dataIndex: 'deliverableNumber',
      align: 'center',
    },
    {
      title: '需要生产数量',
      dataIndex: 'needProduceNumber',
      align: 'center',
    },
  ];
  const columns2: any = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      slotName: 'index',
      width: 80,
    },
    {
      title: '物料编码',
      dataIndex: 'number',
      align: 'center',
      width: 150,
    },
    {
      title: '物料名称',
      dataIndex: 'name',
      align: 'center',
      width: 150,
    },
    {
      title: '规格型号',
      dataIndex: 'spec',
      align: 'center',
      width: 150,
    },
    {
      title: '基本单位',
      dataIndex: 'basicName',
      align: 'center',
      width: 150,
    },
    {
      title: '需求数量',
      dataIndex: 'demandNumber',
      align: 'center',
      width: 150,
    },
    {
      title: '物料来源',
      dataIndex: 'materialStatus',
      align: 'center',
      slotName: 'materialStatus',
      width: 150,
    },
    {
      title: '库存量',
      dataIndex: 'name',
      align: 'center',
      children: [
        {
          title: '库存总量',
          dataIndex: 'totalStock',
          align: 'center',
          width: 150,
        },
        {
          title: '已占用库存量',
          dataIndex: 'occupiedStock',
          align: 'center',
          width: 150,
        },
        {
          title: '空闲库存量',
          dataIndex: 'freeStock',
          align: 'center',
          width: 150,
        },
      ],
    },
    {
      title: '在途数量',
      ataIndex: 'inTransitNumber',
      align: 'center',
      slotName: 'inTransitNumber',
      width: 150,
    },
    {
      title: '标准用量',
      ataIndex: 'dosage',
      align: 'center',
      slotName: 'dosage',
      width: 150,
    },
    {
      title: '损耗率(%)',
      ataIndex: 'wastage',
      align: 'center',
      slotName: 'wastage',
      width: 150,
    },
    {
      title: '物料状态',
      ataIndex: 'materialStatus',
      align: 'center',
      slotName: 'materialStatus',
      width: 150,
    },
    {
      title: '已满足生产数量',
      ataIndex: 'satisfiedProduceNumber',
      align: 'center',
      slotName: 'satisfiedProduceNumber',
      width: 150,
    },
    {
      title: '缺货数量',
      ataIndex: 'outOfStockNumber',
      align: 'center',
      slotName: 'outOfStockNumber',
      width: 150,
    },
    {
      title: '推荐采购数量',
      ataIndex: 'recommendPurchaseNumber',
      align: 'center',
      slotName: 'recommendPurchaseNumber',
      width: 150,
    },
  ];

  let timer: any = 0;
  const timerFn = () => {
    timer = setInterval(() => {
      if (responseTime.value > 0) {
        if (successful.value || responseTime.value > 1) {
          responseTime.value -= 1;
        }
      } else {
        setTimeout(() => {
          hidden.value = false;
        }, 200);
        clearInterval(timer);
      }
    }, setTime);
  };
  const getData = () => {
    return Promise.resolve(productBasic.data);
  };
  const init = async () => {
    try {
      timerFn();
      const res = await Promise.all([
        GetProduceOrderDetails({ id: id.value }),
        GetProduceOrdersMrp({ id: id.value }),
        GetProduceMaterialsMrp({ id: id.value }),
      ]);
      productBasic.data = [res[0]];
      moduleData.data = res[1];
      productDataAll.data = res[2];
      productDataLack.data = res[2]?.filter((ele) => ele.materialStatus === 2);
      successful.value = true;
      setTime = 200;
      clearInterval(timer);
      timerFn();
      tableRef.value?.loadData();
    } catch (err) {
      console.log(err);
      error.value = true;
      Message.error('服务出错');
    }
  };
  const changeVisible = (e: boolean) => {
    materielModalVisible.value = e;
  };
  const updateMaterialData = (data: any) => {
    // materialData.data = cloneDeep(data);
    // tableRef.value.loadData();
  };
  init();

  const confirm = async () => {
    const newArr = cloneDeep(productDataLack.data);
    newArr.forEach((ele: any) => {
      ele.amount = Number(ele.recommendPurchaseNumber);
      delete ele.id;
    });
    buyStore.productionToProcurement = newArr;
    router.push({ name: 'AddApplyPurchase' });
  };
</script>

<style lang="less" scoped>
  .main {
    width: 100%;
    padding: 20px;
    .title {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      .icon {
        background-color: #3d7eff;
        width: 5px;
        height: 20px;
        border-radius: 5px;
        margin-right: 10px;
      }
      p {
        font-size: 16px;
        padding: 0;
        margin: 0;
      }
    }
    .table {
      width: 100%;
      padding: 20px;
      margin-bottom: 20px;
      border-radius: 5px;
      box-shadow: 0 0 5px #d7cece;
    }
  }
  .foot {
    padding-top: 10px;
    margin-top: 10px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }
  .status {
    display: flex;
    justify-content: center;
    align-items: center;
    // background-color: #ff4a4a;
    color: #ff4a4a;
    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
      background-color: #ff4a4a;
      box-shadow: 0px 0px 5px;
    }
  }
  .lack {
    // background-color: #009933;
    color: #009933;
    p {
      background-color: #009933;
    }
  }
</style>
